<template>
  <div class="users-container fade-in">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon">
              <User />
            </el-icon>
            用户管理
          </h2>
          <p class="page-subtitle">管理系统用户、角色和权限分配</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="createUser">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
          <el-button type="success" @click="batchImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="warning" @click="exportUsers">
            <el-icon><Download /></el-icon>
            导出用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ totalUsers }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ activeUsers }}</div>
                <div class="stat-label">活跃用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Lock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ adminUsers }}</div>
                <div class="stat-label">管理员</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ newUsers }}</div>
                <div class="stat-label">本月新增</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-card shadow="hover">
        <div class="filter-content">
          <div class="filter-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名、邮箱或手机号"
              class="search-input"
              clearable
              prefix-icon="Search"
            />
            <el-select v-model="roleFilter" placeholder="角色筛选" clearable>
              <el-option label="全部角色" value="" />
              <el-option label="超级管理员" value="super_admin" />
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
              <el-option label="访客" value="guest" />
            </el-select>
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
              <el-option label="全部状态" value="" />
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="disabled" />
              <el-option label="待激活" value="pending" />
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="注册开始日期"
              end-placeholder="注册结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </div>
          <div class="filter-right">
            <el-button type="primary" plain @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="resetFilters">重置筛选</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 用户列表 -->
    <div class="users-list">
      <el-card shadow="hover">
        <template #header>
          <div class="list-header">
            <div class="header-left">
              <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
              <span class="selected-count" v-if="selectedUsers.length > 0">
                已选择 {{ selectedUsers.length }} 项
              </span>
            </div>
            <div class="header-right">
              <el-button 
                type="success" 
                size="small" 
                :disabled="selectedUsers.length === 0"
                @click="batchEnable"
              >
                <el-icon><Check /></el-icon>
                批量启用
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                :disabled="selectedUsers.length === 0"
                @click="batchDisable"
              >
                <el-icon><Close /></el-icon>
                批量禁用
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                :disabled="selectedUsers.length === 0"
                @click="batchDelete"
              >
                <el-icon><Delete /></el-icon>
                批量删除
              </el-button>
            </div>
          </div>
        </template>

        <el-table 
          :data="filteredUsers" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="avatar" label="头像" width="80">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar" :icon="UserFilled" />
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" min-width="120">
            <template #default="{ row }">
              <div class="user-info">
                <div class="username">{{ row.username }}</div>
                <div class="email">{{ row.email }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="130" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag :type="getRoleTagType(row.role)" size="small">
                {{ getRoleLabel(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastLogin" label="最后登录" width="180">
            <template #default="{ row }">
              {{ formatDate(row.lastLogin) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="注册时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-button size="small" @click="viewUser(row)">
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button size="small" type="primary" @click="editUser(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button size="small" type="success" @click="assignRole(row)">
                  <el-icon><Setting /></el-icon>
                  角色
                </el-button>
                <el-button 
                  size="small" 
                  :type="row.status === 'active' ? 'warning' : 'success'"
                  @click="toggleUserStatus(row)"
                >
                  <el-icon><component :is="row.status === 'active' ? 'Close' : 'Check'" /></el-icon>
                  {{ row.status === 'active' ? '禁用' : '启用' }}
                </el-button>
                <el-button size="small" type="danger" @click="deleteUser(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalUsers"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增用户对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新增用户"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
                <el-option label="超级管理员" value="super_admin" />
                <el-option label="管理员" value="admin" />
                <el-option label="普通用户" value="user" />
                <el-option label="访客" value="guest" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="userForm.password" 
                type="password" 
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="userForm.confirmPassword" 
                type="password" 
                placeholder="请确认密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUser" :loading="submitting">
            创建用户
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="showRoleDialog"
      title="角色分配"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="role-content">
        <div class="current-user">
          <el-avatar :size="60" :src="currentUser?.avatar" :icon="UserFilled" />
          <div class="user-details">
            <h4>{{ currentUser?.username }}</h4>
            <p>{{ currentUser?.email }}</p>
            <p>当前角色: <el-tag :type="getRoleTagType(currentUser?.role)" size="small">
              {{ getRoleLabel(currentUser?.role) }}
            </el-tag></p>
          </div>
        </div>
        
        <div class="role-selection">
          <h4>选择角色</h4>
          <el-radio-group v-model="selectedRole" class="role-options">
            <div class="role-option" v-for="role in roles" :key="role.value">
              <el-radio :label="role.value">
                <div class="role-info">
                  <div class="role-name">{{ role.label }}</div>
                  <div class="role-desc">{{ role.description }}</div>
                  <div class="role-permissions">
                    <el-tag 
                      v-for="perm in role.permissions" 
                      :key="perm" 
                      size="small" 
                      type="info"
                    >
                      {{ perm }}
                    </el-tag>
                  </div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmRoleAssignment" :loading="assigning">
            确认分配
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入用户"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <div class="import-description">
          <p>请选择要导入的Excel文件：</p>
          <p class="import-info">支持.xlsx格式，文件应包含：用户名、邮箱、手机号、角色等字段。</p>
          <p class="import-template">
            <el-button type="primary" link @click="downloadTemplate">
              <el-icon><Download /></el-icon>
              下载导入模板
            </el-button>
          </p>
        </div>

        <div class="import-upload">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept=".xlsx,.xls"
            drag
          >
            <el-icon class="el-icon--upload"><Upload /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或 <em>点击上传</em>
            </div>
          </el-upload>
          <div v-if="importFile" class="import-file-info">
            <el-icon><Document /></el-icon>
            <span>{{ importFile.name }} ({{ (importFile.size / 1024).toFixed(2) }} KB)</span>
          </div>
        </div>

        <div class="import-preview" v-if="importPreview.length > 0">
          <h4>导入预览 ({{ importPreview.length }} 条记录)</h4>
          <el-table :data="importPreview" style="width: 100%" max-height="200">
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="phone" label="手机号" width="130" />
            <el-table-column prop="role" label="角色" width="100">
              <template #default="{ row }">
                <el-tag :type="getRoleTagType(row.role)" size="small">
                  {{ getRoleLabel(row.role) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmImport" :loading="importing">
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  User, Plus, Upload, Download, UserFilled, Lock, Clock, Search, Refresh,
  Delete, View, Edit, Setting, Check, Close, Document
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const assigning = ref(false)
const importing = ref(false)
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const selectAll = ref(false)
const selectedUsers = ref([])
const showCreateDialog = ref(false)
const showRoleDialog = ref(false)
const showImportDialog = ref(false)
const currentUser = ref(null)
const selectedRole = ref('')
const importFile = ref(null)
const importPreview = ref([])
const userFormRef = ref(null)
const uploadRef = ref(null)

// 表单数据
const userForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  role: '',
  realName: '',
  department: '',
  remark: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 角色配置
const roles = ref([
  {
    value: 'super_admin',
    label: '超级管理员',
    description: '拥有系统所有权限，可以管理其他管理员',
    permissions: ['用户管理', '角色管理', '系统设置', '数据管理', '日志查看']
  },
  {
    value: 'admin',
    label: '管理员',
    description: '拥有大部分管理权限，可以管理普通用户',
    permissions: ['用户管理', '数据管理', '报告管理']
  },
  {
    value: 'user',
    label: '普通用户',
    description: '可以查看和操作自己的数据',
    permissions: ['数据查看', '报告查看', '个人信息管理']
  },
  {
    value: 'guest',
    label: '访客',
    description: '只能查看公开数据',
    permissions: ['数据查看']
  }
])

// 模拟数据
const users = ref([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    phone: '13800138000',
    role: 'super_admin',
    status: 'active',
    realName: '系统管理员',
    department: '技术部',
    avatar: null,
    lastLogin: '2024-01-15 10:30:00',
    createdAt: '2023-01-01 00:00:00',
    remark: '系统超级管理员'
  },
  {
    id: 2,
    username: 'manager',
    email: 'manager@example.com',
    phone: '13800138001',
    role: 'admin',
    status: 'active',
    realName: '张经理',
    department: '运营部',
    avatar: null,
    lastLogin: '2024-01-14 15:20:00',
    createdAt: '2023-06-15 09:00:00',
    remark: '运营部经理'
  },
  {
    id: 3,
    username: 'user001',
    email: 'user001@example.com',
    phone: '13800138002',
    role: 'user',
    status: 'active',
    realName: '李用户',
    department: '市场部',
    avatar: null,
    lastLogin: '2024-01-13 14:10:00',
    createdAt: '2023-12-01 10:30:00',
    remark: '普通用户'
  },
  {
    id: 4,
    username: 'guest001',
    email: 'guest001@example.com',
    phone: '13800138003',
    role: 'guest',
    status: 'disabled',
    realName: '王访客',
    department: '外部',
    avatar: null,
    lastLogin: '2024-01-10 11:00:00',
    createdAt: '2024-01-05 16:45:00',
    remark: '外部访客'
  }
])

// 计算属性
const totalUsers = computed(() => users.value.length)
const activeUsers = computed(() => users.value.filter(u => u.status === 'active').length)
const adminUsers = computed(() => users.value.filter(u => u.role === 'admin' || u.role === 'super_admin').length)
const newUsers = computed(() => users.value.filter(u => {
  const createdAt = new Date(u.createdAt)
  const now = new Date()
  return createdAt.getMonth() === now.getMonth() && createdAt.getFullYear() === now.getFullYear()
}).length)

const filteredUsers = computed(() => {
  let filtered = users.value

  if (searchQuery.value) {
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      user.phone.includes(searchQuery.value)
    )
  }

  if (roleFilter.value) {
    filtered = filtered.filter(user => user.role === roleFilter.value)
  }

  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }

  if (dateRange.value && dateRange.value.length === 2) {
    filtered = filtered.filter(user => {
      const createdAt = new Date(user.createdAt)
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      return createdAt >= startDate && createdAt <= endDate
    })
  }

  return filtered
})

// 方法
const getRoleTagType = (role) => {
  const types = {
    super_admin: 'danger',
    admin: 'warning',
    user: 'primary',
    guest: 'info'
  }
  return types[role] || 'info'
}

const getRoleLabel = (role) => {
  const labels = {
    super_admin: '超级管理员',
    admin: '管理员',
    user: '普通用户',
    guest: '访客'
  }
  return labels[role] || role
}

const getStatusTagType = (status) => {
  const types = {
    active: 'success',
    disabled: 'danger',
    pending: 'warning'
  }
  return types[status] || 'info'
}

const getStatusLabel = (status) => {
  const labels = {
    active: '正常',
    disabled: '禁用',
    pending: '待激活'
  }
  return labels[status] || status
}

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const createUser = () => {
  showCreateDialog.value = true
  userForm.value = {
    username: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    role: '',
    realName: '',
    department: '',
    remark: ''
  }
}

const submitUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newUser = {
      id: Date.now(),
      username: userForm.value.username,
      email: userForm.value.email,
      phone: userForm.value.phone,
      role: userForm.value.role,
      status: 'active',
      realName: userForm.value.realName,
      department: userForm.value.department,
      avatar: null,
      lastLogin: null,
      createdAt: new Date().toLocaleString('zh-CN'),
      remark: userForm.value.remark
    }
    
    users.value.unshift(newUser)
    ElMessage.success('用户创建成功')
    showCreateDialog.value = false
  } catch (error) {
    ElMessage.error('请检查表单信息')
  } finally {
    submitting.value = false
  }
}

const viewUser = (user) => {
  ElMessage.info(`查看用户: ${user.username}`)
}

const editUser = (user) => {
  ElMessage.info(`编辑用户: ${user.username}`)
}

const assignRole = (user) => {
  currentUser.value = user
  selectedRole.value = user.role
  showRoleDialog.value = true
}

const confirmRoleAssignment = async () => {
  if (!selectedRole.value) {
    ElMessage.warning('请选择角色')
    return
  }
  
  assigning.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const user = users.value.find(u => u.id === currentUser.value.id)
    if (user) {
      user.role = selectedRole.value
    }
    
    ElMessage.success('角色分配成功')
    showRoleDialog.value = false
  } finally {
    assigning.value = false
  }
}

const toggleUserStatus = async (user) => {
  const newStatus = user.status === 'active' ? 'disabled' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.username}" 吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    user.status = newStatus
    ElMessage.success(`${action}成功`)
  } catch {
    // 用户取消操作
  }
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = users.value.findIndex(u => u.id === user.id)
    if (index > -1) {
      users.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
  selectAll.value = selection.length === filteredUsers.value.length
}

const handleSelectAll = (val) => {
  if (val) {
    selectedUsers.value = [...filteredUsers.value]
  } else {
    selectedUsers.value = []
  }
}

const batchEnable = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要启用的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量启用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    selectedUsers.value.forEach(user => {
      user.status = 'active'
    })
    selectedUsers.value = []
    selectAll.value = false
    ElMessage.success('批量启用成功')
  } catch {
    // 用户取消操作
  }
}

const batchDisable = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要禁用的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量禁用',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    selectedUsers.value.forEach(user => {
      user.status = 'disabled'
    })
    selectedUsers.value = []
    selectAll.value = false
    ElMessage.success('批量禁用成功')
  } catch {
    // 用户取消操作
  }
}

const batchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedUsers.value.map(u => u.id)
    users.value = users.value.filter(u => !ids.includes(u.id))
    selectedUsers.value = []
    selectAll.value = false
    ElMessage.success('批量删除成功')
  } catch {
    // 用户取消删除
  }
}

const batchImport = () => {
  showImportDialog.value = true
  importFile.value = null
  importPreview.value = []
}

const handleFileChange = (file) => {
  importFile.value = file.raw
  // 模拟预览数据
  importPreview.value = [
    { username: 'newuser1', email: 'newuser1@example.com', phone: '13800138010', role: 'user' },
    { username: 'newuser2', email: 'newuser2@example.com', phone: '13800138011', role: 'user' },
    { username: 'newuser3', email: 'newuser3@example.com', phone: '13800138012', role: 'guest' }
  ]
}

const confirmImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  
  importing.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟导入新用户
    importPreview.value.forEach((user, index) => {
      const newUser = {
        id: Date.now() + index,
        username: user.username,
        email: user.email,
        phone: user.phone,
        role: user.role,
        status: 'active',
        realName: '',
        department: '',
        avatar: null,
        lastLogin: null,
        createdAt: new Date().toLocaleString('zh-CN'),
        remark: '批量导入'
      }
      users.value.push(newUser)
    })
    
    ElMessage.success(`成功导入 ${importPreview.value.length} 个用户`)
    showImportDialog.value = false
  } finally {
    importing.value = false
  }
}

const downloadTemplate = () => {
  ElMessage.success('模板下载开始')
}

const exportUsers = () => {
  ElMessage.success('用户数据导出成功')
}

const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}

const resetFilters = () => {
  searchQuery.value = ''
  roleFilter.value = ''
  statusFilter.value = ''
  dateRange.value = []
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.users-container {
  padding: var(--spacing-lg);
  background: var(--bg-primary);
  min-height: 100vh;
}

.page-header {
  margin-bottom: var(--spacing-xl);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.title-icon {
  font-size: 1.5rem;
  color: var(--primary-color);
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: var(--spacing-md);
}

/* 统计卡片 */
.stats-section {
  margin-bottom: var(--spacing-xl);
}

.stat-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.stat-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: var(--spacing-xl);
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-md);
}

.filter-left {
  display: flex;
  gap: var(--spacing-md);
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-right {
  display: flex;
  gap: var(--spacing-md);
}

/* 用户列表 */
.users-list {
  margin-bottom: var(--spacing-xl);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.selected-count {
  color: var(--primary-color);
  font-size: 0.9rem;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.username {
  font-weight: 500;
  color: var(--text-primary);
}

.email {
  font-size: 0.8rem;
  color: var(--text-secondary);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-lg);
}

/* 角色分配对话框 */
.role-content {
  padding: var(--spacing-lg) 0;
}

.current-user {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-lg);
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  margin-bottom: var(--spacing-xl);
}

.user-details h4 {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: 1.1rem;
}

.user-details p {
  margin: 0 0 var(--spacing-xs) 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.role-selection h4 {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--text-primary);
  font-size: 1rem;
  font-weight: 600;
}

.role-options {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.role-option {
  border: 2px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  transition: all 0.3s ease;
}

.role-option:hover {
  border-color: var(--primary-color);
  background: rgba(99, 102, 241, 0.05);
}

.role-option .el-radio {
  width: 100%;
  margin: 0;
}

.role-info {
  margin-left: var(--spacing-md);
}

.role-name {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.role-desc {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-bottom: var(--spacing-sm);
}

.role-permissions {
  display: flex;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

/* 导入对话框 */
.import-content {
  padding: var(--spacing-lg) 0;
}

.import-description p {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--text-primary);
  font-size: 0.9rem;
}

.import-info {
  color: var(--text-secondary) !important;
  font-size: 0.8rem !important;
}

.import-template {
  margin-top: var(--spacing-md);
}

.import-upload {
  margin: var(--spacing-lg) 0;
}

.import-file-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  margin-top: var(--spacing-md);
}

.import-file-info .el-icon {
  color: var(--primary-color);
  font-size: 1.2rem;
}

.import-preview {
  margin-top: var(--spacing-lg);
}

.import-preview h4 {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--text-primary);
  font-size: 1rem;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .users-container {
    padding: var(--spacing-md);
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-left {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }

  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-md);
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 1.25rem;
  }

  .current-user {
    flex-direction: column;
    text-align: center;
  }

  .role-option {
    padding: var(--spacing-md);
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }

  .stat-number {
    font-size: 1.5rem;
  }
}
</style>
